package cn.iocoder.yudao.module.forward.controller.app.scope;

import cn.hutool.crypto.SecureUtil;
import cn.iocoder.yudao.module.forward.controller.app.register.vo.ResultRespVO;
import cn.iocoder.yudao.module.forward.controller.app.scope.vo.*;
import cn.iocoder.yudao.module.forward.dal.dataobject.broker.BrokerDO;
import cn.iocoder.yudao.module.forward.dal.dataobject.group.GroupDO;
import cn.iocoder.yudao.module.forward.dal.dataobject.license.LicenseDO;
import cn.iocoder.yudao.module.forward.dal.dataobject.scope.ScopeDO;
import cn.iocoder.yudao.module.forward.service.broker.BrokerService;
import cn.iocoder.yudao.module.forward.service.group.GroupService;
import cn.iocoder.yudao.module.forward.service.license.LicenseService;
import cn.iocoder.yudao.module.forward.service.scope.ScopeService;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Tag(name = "终端注册 APP - 授权接口")
@RestController
@RequestMapping("/register")
@Validated
public class AuthorizeController {
    @Resource
    private LicenseService licenseService;
    @Resource
    private GroupService groupService;
    @Resource
    private ScopeService scopeService;
    @Resource
    private BrokerService brokerService;

    @PostMapping("/tm_authorize")
    @Operation(summary = "授权申请")
    @PermitAll
    public String tm_authorize(HttpServletRequest request) throws IOException {
        ResultRespVO resultRespVO = new ResultRespVO();

        AuthorizeReqVO authorizeReqVO = null;
        if("application/x-www-form-urlencoded".equals(request.getContentType())){
            authorizeReqVO = new AuthorizeReqVO();
            authorizeReqVO.setClientId(request.getParameter("clientId"));
            authorizeReqVO.setUname(request.getParameter("uname"));
            authorizeReqVO.setPwd(request.getParameter("pwd"));
            authorizeReqVO.setScope(request.getParameter("scope"));
        }else if("application/json".equals(request.getContentType())){
            ObjectMapper mapper = new ObjectMapper();
            authorizeReqVO = mapper.readValue(request.getInputStream(), AuthorizeReqVO.class);
        }else{
            resultRespVO.setResult("请求content-type错误");
            return JSONObject.toJSONString(resultRespVO);
        }

        LicenseDO licenseDO = licenseService.getLicenseRegister(authorizeReqVO);
        if(licenseDO==null){
            resultRespVO.setResult("未查询到终端信息");
            return JSONObject.toJSONString(resultRespVO);
        }else{
            GroupDO group = groupService.getGroup(licenseDO.getGroupId());
            List<ScopeDO> scopes = scopeService.getScopeByGroupId(group.getId());
            ArrayList<ScopeRespVO> scopeRespVOS = new ArrayList<>();
            for(ScopeDO scope:scopes){
                List<String> strings = Arrays.asList(authorizeReqVO.getScope().replaceAll(" ", "")
                        .replaceAll("，", ",").trim().split(","));
                if(strings.contains(scope.getScope())){
                    ScopeRespVO scopeRespVO = new ScopeRespVO();
                    BrokerDO broker = brokerService.getBroker(scope.getBrokerId());
                    scopeRespVO.setMqtthost(broker.getOutsideIp());
                    scopeRespVO.setPort(String.valueOf(broker.getOutsidePort()));
                    scopeRespVO.setTopic(scope.getTopic());
                    scopeRespVO.setScope(scope.getScope());
                    scopeRespVOS.add(scopeRespVO);
                }
            }
            resultRespVO.setResult(scopeRespVOS);
            return JSONObject.toJSONString(resultRespVO);
        }
    }

    @PostMapping("/tm_cancelAuth")
    @Operation(summary = "授权撤销")
    @PermitAll
    public String tm_cancelAuth(HttpServletRequest request) throws IOException {
        ResultRespVO resultRespVO = new ResultRespVO();

        CancelAuthReqVO cancelAuthReqVO = null;
        if("application/x-www-form-urlencoded".equals(request.getContentType())){
            cancelAuthReqVO = new CancelAuthReqVO();
            cancelAuthReqVO.setClientId(request.getParameter("clientId"));
            cancelAuthReqVO.setUname(request.getParameter("uname"));
            cancelAuthReqVO.setPwd(request.getParameter("pwd"));
            cancelAuthReqVO.setScope(request.getParameter("Scope"));
        }else if("application/json".equals(request.getContentType())){
            ObjectMapper mapper = new ObjectMapper();
            cancelAuthReqVO = mapper.readValue(request.getInputStream(), CancelAuthReqVO.class);
        }else{
            resultRespVO.setResult("请求content-type错误");
            return JSONObject.toJSONString(resultRespVO);
        }

        LicenseDO licenseDO = licenseService.getLicenseRegister(cancelAuthReqVO);
        if(licenseDO==null){
            resultRespVO.setResult("未查询到终端信息");
            return JSONObject.toJSONString(resultRespVO);
        }else{
            GroupDO group = groupService.getGroup(licenseDO.getGroupId());
            List<ScopeDO> scopes = scopeService.getScopeByGroupId(group.getId());
            ArrayList<CancelAuthRespVO> ancelAuthRespVOS = new ArrayList<>();
            for(ScopeDO scope:scopes){
                List<String> strings = Arrays.asList(cancelAuthReqVO.getScope().replaceAll(" ", "")
                        .replaceAll("，", ",").trim().split(","));
                if(strings.contains(scope.getScope())){
                    CancelAuthRespVO scopeRespVO = new CancelAuthRespVO();
                    scopeRespVO.setScope(scope.getScope());
                    scopeRespVO.setResult("成功");
                    ancelAuthRespVOS.add(scopeRespVO);
                }
            }
            resultRespVO.setResult(ancelAuthRespVOS);
            return JSONObject.toJSONString(resultRespVO);
        }
    }

    @PostMapping("/tm_getTokenInfo")
    @Operation(summary = "授权查询")
    @PermitAll
    public String tm_getTokenInfo(HttpServletRequest request) throws IOException {
        ResultRespVO resultRespVO = new ResultRespVO();

        AuthorizeReqVO authorizeReqVO = null;
        if("application/x-www-form-urlencoded".equals(request.getContentType())){
            authorizeReqVO = new AuthorizeReqVO();
            authorizeReqVO.setClientId(request.getParameter("clientId"));
            authorizeReqVO.setUname(request.getParameter("uname"));
            authorizeReqVO.setPwd(request.getParameter("pwd"));
            authorizeReqVO.setScope(request.getParameter("scope"));
        }else if("application/json".equals(request.getContentType())){
            ObjectMapper mapper = new ObjectMapper();
            authorizeReqVO = mapper.readValue(request.getInputStream(), AuthorizeReqVO.class);
        }else{
            resultRespVO.setResult("请求content-type错误");
            return JSONObject.toJSONString(resultRespVO);
        }

        LicenseDO licenseDO = licenseService.getLicenseRegister(authorizeReqVO);
        if(licenseDO==null){
            resultRespVO.setResult("未查询到终端信息");
            return JSONObject.toJSONString(resultRespVO);
        }else{
            GroupDO group = groupService.getGroup(licenseDO.getGroupId());
            List<ScopeDO> scopes = scopeService.getScopeByGroupId(group.getId());
            ArrayList<TokenInfoRespVO> tokenInfoRespVOS = new ArrayList<>();
            for(ScopeDO scope:scopes){
                List<String> strings = Arrays.asList(authorizeReqVO.getScope().replaceAll(" ", "")
                        .replaceAll("，", ",").trim().split(","));
                if(strings.contains(scope.getScope())){
                    TokenInfoRespVO tokenInfoRespVO = new TokenInfoRespVO();
                    tokenInfoRespVO.setClientId(licenseDO.getClientId());
                    tokenInfoRespVO.setToken(SecureUtil.md5("asd"));
                    tokenInfoRespVO.setScope(scope.getScope());
                    tokenInfoRespVO.setCreate_at(DateUtils.format(new Date(System.currentTimeMillis()-10*60*1000),"yyyy-MM-dd HH:mm:ss"));
                    tokenInfoRespVO.setTopic(scope.getTopic());
                    BrokerDO broker = brokerService.getBroker(scope.getBrokerId());
                    tokenInfoRespVO.setMqtthost(broker.getOutsideIp());
                    tokenInfoRespVO.setPort(String.valueOf(broker.getOutsidePort()));
                    tokenInfoRespVOS.add(tokenInfoRespVO);
                }
            }
            resultRespVO.setResult(tokenInfoRespVOS);
            return JSONObject.toJSONString(resultRespVO);
        }
    }
}
